package com.cet.qz.unit01.chapter1_3;

import java.util.Iterator;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2021-03-19 21:03
 **/
public class SimpleStackTest {
    /*
    *  Exception: java.lang.ArrayStoreException
    *  solution: new Object[]时，注意使用java.lang包下的
    *
    * */

    public static void main(String[] args) {
        ResizingArrayStack<String> strings = new ResizingArrayStack<String>();
        strings.push("aa");
        strings.push("bb");
        strings.push("cc");
        strings.push("aa");
        strings.push("bb");
        strings.push("cc");
        String pop1 = strings.pop();
        System.out.println(pop1);
        System.out.println("==========");
        for (String string : strings) {
            System.out.println(string);
        }
        System.out.println("=========");
        System.out.println(strings.size());
    }
}

class ResizingArrayStack<Item> implements Iterable<Item> {

    private Item[] a = (Item[]) new Object[1];
    private int N = 0; //栈顶指针

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    /*
     *方法描述： 改变栈容量，实质为将数组深拷贝到另一个数组
     *
     * @param max
     * @return void
     * @author chenentao
     * @date 2021/3/19 21:10
     */
    public void resize(int max) {
        Item[] items = (Item[]) new Object[max];
        for (int i = 0; i < N; i++) {
            items[i] = a[i];
        }
        a = items;
    }

    public void push(Item item) {
        if (N == a.length) {
            resize(2 * a.length);
        }
        a[N++] = item;
    }

    public Item pop() {
        Item item = a[--N];
        a[N] = null; //游离对象回收
        if ( !isEmpty() && N == a.length / 4) {
            resize(a.length / 2);
        }
        return item;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ReverseArrayIterator();
    }

    private class ReverseArrayIterator implements Iterator<Item> {

        private int i = N;

        @Override
        public boolean hasNext() {
            return i > 0;
        }

        @Override
        public Item next() {
            return a[--i];
        }

        @Override
        public void remove() {

        }
    }

}
